package com.supper.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author yutao
 * @since 2020/4/14 3:23 下午
 */
@Component
public class MyAspectAutoProxy implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        final Object obj = bean;
        if (bean instanceof Calculator) {
            return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("开始计算。。。。");
                            Object result = method.invoke(obj, args);
                            System.out.println("结束计算。。。。");
                            return result;
                        }
                    });
        }
        return obj;
    }
}
